package com.test.service.Impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;

import org.springframework.stereotype.Service;

import com.test.model.BaseCode;
import com.test.service.CodeService;

@Service
public class CodeServiceImpl implements CodeService {

	private static Map<String, List<BaseCode>> entityCodeEntities = new HashMap<String, List<BaseCode>>();
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	public Object get(String entityName) {
		return entityCodeEntities.get(entityName);
	}
	
	@Override
	public Object get(String entityName, String code) {
		@SuppressWarnings("unchecked")
		List<BaseCode> codeEntities = (List<BaseCode>) get(entityName);
		for (BaseCode codeEntity : codeEntities) {
			if (codeEntity.getCode().equals(code)) {
				return codeEntity;
			}
		}
		return null;
	}
	
	@PostConstruct
	@SuppressWarnings("unchecked")
	public void initializeCodeEntities() {
		Metamodel model = entityManager.getEntityManagerFactory().getMetamodel();
		for (EntityType<?> entityType : model.getEntities()) {
			String entityName = entityType.getName();
			Class<?> entityRealType = entityType.getBindableJavaType();
			if (BaseCode.class.isAssignableFrom(entityRealType) && BaseCode.class != entityRealType) {
				List<BaseCode> codeEntities = entityManager.createQuery("from " + entityName + " c").getResultList();
				entityCodeEntities.put(entityName, codeEntities);
			}
		}
	}
}
